package org.cash.service;

import cn.hutool.core.lang.Assert;
import org.cash.cashrule.CashSuper;
import org.cash.factory.CashFactory;
import org.cash.strategy.CashContext;

import java.math.BigDecimal;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

//计算总价入口
public class CashCalculatorService {
    //水果单价
    private final static Map<String, Double> fruitPrice = Stream.of(new Object[][]{
            {"APPLE", 8d}, {"BERRIES", 13d}, {"MANGO", 20d}
    }).collect(Collectors.toMap(data -> (String) data[0], data -> (Double) data[1]));


    /**
     * 获取总价线 工厂模式
     *
     * @param weight    重量
     * @param fruitType 水果类型
     * @param ruleType  计价规则
     * @return
     */
    public BigDecimal getTotalCashFactory(int weight, String fruitType, String ruleType) {
        Assert.isTrue(weight >= 0d, "weight参数小于0");
        //工厂模式下
        BigDecimal totalPrice = this.getTotalPrice(weight, fruitType);
        CashSuper adapter = CashFactory.createCashAdapter(ruleType);
        return adapter.acceptCash(totalPrice);
    }

    /**
     * 获取总价线 策略模式
     *
     * @param weight    重量
     * @param fruitType 水果类型
     * @param ruleType  计价规则
     * @return
     */
    public BigDecimal getTotalCashStratery(int weight, String fruitType, String ruleType) {
        Assert.isTrue(weight >= 0d, "weight参数小于0");
        BigDecimal totalPrice = this.getTotalPrice(weight, fruitType);
        return new CashContext(ruleType).getCash(totalPrice);
    }

    //从数据库获取或集合中获取
    private BigDecimal getTotalPrice(int weight, String type) {
        Double price = fruitPrice.getOrDefault(type, null);
        Assert.notNull(price, "单价为空");
        return new BigDecimal(weight).multiply(new BigDecimal(price));
    }
}
